<?php

/**
 * This is controller use for fanpage tab area
 * @author: hungnq@younetco.com
 * @version: 0.1
 */
class Tab_IndexController extends YouNet_Controller_Tab_Action implements Core_Model_IEntryFields
{

	protected $_id_contest;
	/**
	 *
	 * @var Core_Model_Contest
	 */
	protected $_contest;
	protected $_is_allow_submit;
	private $_skin;

	protected function _getContest()
	{
		$key = Core_Cache_IKeys::MEMCACHE_MODEL_CONTEST.$this->_id_contest;
		$contest		= null;
		$contestData	= YouNet_Util::getMemCache()->load($key);
		if( $contestData === false)
		{
			if( !empty($this->_id_contest) )
			{
				$contestTbl		= Core_Model_DbTable_Contests::getInstance();
				$contest		= $contestTbl->findOne($this->_id_contest);
			}
			if( empty($contest->id) )
			{
				$contestTbl = Core_Model_DbTable_Contests::getInstance();
				$contest	= $contestTbl->createRow();
			}
			else
			{
				YouNet_Util::getMemCache()->save($contest->toArray(), $key);
			}
		}
		else
		{
			$contestTbl = Core_Model_DbTable_Contests::getInstance();
			$contest	= $contestTbl->createRow($contestData);
		}
		return $contest;
	}

	public function _updateCachedContest()
	{
		$key = Core_Cache_IKeys::MEMCACHE_MODEL_CONTEST.$this->_id_contest;
		YouNet_Util::getMemCache()->save($this->_contest->toArray(), $key);
	}

	private function _processParams()
	{
		if( $this->_params )
		{
			$arrParams = $this->_params;
			if( isset($arrParams['module']) )
			{
				unset($arrParams['module']);
			}
			if( isset($arrParams['controller']) )
			{
				unset($arrParams['controller']);
			}
			if( isset($arrParams['action']) )
			{
				unset($arrParams['action']);
			}
			if( isset($arrParams['id_user']) )
			{
				unset($arrParams['id_user']);
			}
			if( isset($arrParams['id_social']) )
			{
				unset($arrParams['id_social']);
			}
			$this->view->arrParams		= $arrParams;
		}
	}
    public function init(){
        parent::init();
		$pagesTable = Core_Model_DbTable_Pages::getInstance();

		//TODO: need to optimize this, due to fowarding preDispatch will run twice
		$this->_id_contest		= YouNet_Util::getMemCache()->load(Core_Cache_IKeys::MEMCACHE_PAPGE_WITH_CONTEST.$this->_id_page);
		if( !$this->_id_contest )
		{
			$this->_id_contest	= $pagesTable->findIdContestByPage($this->_id_page);
			YouNet_Util::getMemCache()->save($this->_id_contest, Core_Cache_IKeys::MEMCACHE_PAPGE_WITH_CONTEST.$this->_id_page);
		}
		$this->_contest		= $this->_getContest();
        $this->_initLanguage();		
    }

	public function preDispatch()
	{
		parent::preDispatch();
        
		$this->_processParams();
		$this->_skin			= SKIN_DEFAULT;
		$this->view->target 	= $this->_getParam('target', 'home');
		$this->_helper->layout->setLayout('tab_' . strtolower($this->_social->getName()));

		$this->view->contest	= $this->_contest;
        /**
         * @deprecated since version 3.0 by <phutp@younetco.com> Should not put id_user &id_page to view
         */
		$this->view->id_user	= $this->_id_user;
        $this->view->id_page	= $this->_id_page;
        $this->view->SKIN		= $this->_skin;
		
		if(!empty($this->_contest->skin))
		{
			$this->view->headLink()->appendStylesheet(STATIC_URL . '/media/skin/template/' . $this->_contest->skin . '?v='.SKIN_VERSION);
		}
	}
    
    private function _initLanguage()
	{
		$language	= $this->_contest->getLanguage();		
		Zend_Registry::set('language',$language);
        
		if( APP_INSTANCE == APP_INSTANCE_VIDEO)
		{
			$file		= APPLICATION_PATH.'/modules/Tab/languages/'.$language.'/main-video.csv';
		}
		else
		{
			$file		= APPLICATION_PATH.'/modules/Tab/languages/'.$language.'/main-image.csv';
		}
		if( file_exists($file) )
		{
			$translate	= Zend_Registry::get('Zend_Translate'); 
			$translate->addTranslation(
				array(
					'adapter'		=> 'csv', 
					'content'		=> $file,
					'locale'		=> 'en',
					'delimiter'		=> ';'
				)
			);
		}
	}
	
	protected function _getRedirectUrlForAuthorization()
	{
		if(isset($this->_params['id_entry']))
		{
			return '/contest/entry/view/id_entry/' . $this->_params['id_entry'];
		}
		else
		{
			return '/';
		}
	}

	public function indexAction()
	{
		$target = $this->_getParam('target');

		$this->view->is_allow_submit	=  $is_allow_submit = $this->_contest->isAllowedSubmit();
		$this->view->is_allow_view		=  $is_allow_view	= $this->_contest->isAllowedView();
		$this->view->is_allow_vote_view =  $this->_contest->isAllowedVoteView();
		$this->view->shareRow = Core_Model_DbTable_Shares::getInstance()->getShareContent($this->_id_contest, $this->_id_page);
		$this->view->render('placeholders/menu_submit_entry.phtml');

		if($this->_contest->isPublished())
		{
            if(!$this->_request->isXmlHttpRequest() && $target != "vote"){
                if($this->_contest->is_need_to_like && !$this->_social->hasLikedPage())
                {
                    $target = 'like';
                }
            }
			if(empty($this->_id_contest))
			{
				$target = 'about';
			}

			if(!$this->_getParam('skip'))
			{
				$target = isset($target) ? $target : $this->_contest->getDefaultTarget();
				$view = $target?$target:'view';
				$this->_helper->viewRenderer->setRender($view);
				switch($target)
				{
					case 'view':
						$this->_viewAction();
						break;
					case 'detail':
						$this->_detailAction();
						break;
					case 'submit':
						$this->_submitAction();
						break;
					case 'winners':
						$this->_winnersAction();
						break;
					case 'image':
						$this->_imageAction();
						break;
					case 'like':
						$this->_likeAction();
						break;
					case 'vote':
						$this->voteAction();
						break;
					case 'about':
					default:
						$this->render('about');
						break;
				}
			}
		}
		else
		{
			$this->render('about');
		}
	}

	protected function _viewAction()
	{
        $keyword		= trim($this->_getParam('keyword', ''));
		$criteria		= intval($this->_getParam('criteria', 1));
        $sort           = $this->_getParam('sort',$this->_contest->getViewEntriesDefault());
        $page			= intval($this->_getParam('page', 1));
		
		/*is using for display search box when search result has only 1 page*/
        $isDisplaySearch= false;

		$values				= array();
		$values['keyword']	= $keyword;
		$values['criteria'] = $criteria;

		$form = new Tab_Form_Search();
		$form->setAction(
			$this->view->pageUrl(array(
				'module'	=> 'tab',
				'target'	=> 'view',
				'page'		=> 1,
				'sort'		=> $sort,
                'keyword'   => null
			))
		);
		$form->populate($values);

		if($keyword!='' && !empty($criteria))
		{
			$isDisplaySearch = true;
		}

		if(isset($_POST['form_submitted']))
		{
			if($form->isValid($_POST))
			{
				$keyword  = $form->getValue('keyword');
				$criteria = $form->getValue('criteria');
			}
		}

		$entriesModel	= new Core_Model_DbTable_Entries();
        $arrListItemsCount  = array('current_page' => $page, 'total_pages' => 0, 'from_items' => 0, 'to_items' => 0);
        $is_random = empty($this->_params['id_entry'])?true:false;
		$paginator		= $entriesModel->searchEntries($this->_id_contest, $keyword, $criteria, $sort, $arrListItemsCount, $is_random);
        if($arrListItemsCount['total_pages'] > 1) {
            $isDisplaySearch = true;
        }
        
		$params = array();
		$page_params = array('target' => 'view');
		if(!empty($page))
		{
			$params['page']		= $page;
		}

		if(!empty($keyword))
		{
			$params['keyword']	= $keyword;
			$page_params['keyword']	= $keyword;
		}
        else
        {
            $params['keyword']	= null;
			$page_params['keyword']	= null;
        }

		if(!empty($criteria))
		{
			$params['criteria']	= $criteria;
			$page_params['criteria']	= $criteria;
		}

        $this->view->paginator		= $paginator;
		$this->view->id_contest		= $this->_id_contest;
		$this->view->page			= $page;
		$this->view->extraValues	= $params;
		$this->view->pageValues		= $page_params;
		$this->view->target 		= $this->_getParam('target');
        $this->view->messages       = $this->_helper->flashMessenger->getMessages();
        $this->view->isDisplaySearch= $isDisplaySearch;
        $this->view->form           = $form;
        $this->view->sort           = $sort;
        $this->view->arrListItemsCount  = $arrListItemsCount;
	}

	/**
	 * This action is used for display entry detail including
	 * image, description, vote numbers
	 */
	protected function _detailAction()
	{
        $this->_viewAction();
        $this->view->first = 1;
        $this->view->last = $this->view->arrListItemsCount['current_page'];
        $this->view->current = $this->view->arrListItemsCount['total_pages'];
        
		$id_entry = $this->_getParam('id_entry', null);
	
        if (empty($id_entry))
        {
            if($this->view->sort == Core_Model_DbTable_Entries::ENTRIES_RANDOM){
                $current_item = $this->view->paginator[0];
            } else {
                $current_item = $this->view->paginator->getItem(1);
            }
            if (!empty($current_item))
            {
                $id_entry = $current_item->id;
            }
        }
			
		if(isset($id_entry) && isset($this->_id_contest))
		{
			$entriesTable = new Core_Model_DbTable_Entries();
			
			$ns = Zend_Registry::get('session');
			if (!isset($ns->prevent_record_view) || !in_array($id_entry, $ns->prevent_record_view))
			{
				$viewParam = array(
					'id_entry'	=> $id_entry,
					'time_viewed'	=> time(),
					'ip'	=> "'".$_SERVER['REMOTE_ADDR']."'"
				);
				$ns = Zend_Registry::get('session');
				if (isset($ns->id_user_ref))
					$viewParam['id_ref_user'] = $ns->id_user_ref;
				if (isset($this->_id_user))
					$viewParam['id_user']	= $this->_id_user;
			
				$entriesTable->addView($viewParam);
				$entriesTable->increaseView($id_entry);
				if (!isset($ns->prevent_record_view))
					$ns->prevent_record_view = array($id_entry);
				else
					$ns->prevent_record_view[] = $id_entry;
			}
            
			$entry = $entriesTable->getEntryDetailForFanPage($id_entry);
            
			if(empty($entry))
			{
                $str_message = "MGS_ENTRY_CAN_NOT_FOUND";
                $this->_helper->flashMessenger->addMessage($str_message);
				YouNet_Util::parentRedirect($this->_social->pageUrl(array('target' => 'view')));
			}
			
			if( !in_array($this->_social->getIdPage(), $this->_contest->getArrIdPages()) )
			{
				YouNet_Util::parentRedirect($this->_social->pageUrl(array('target' => 'view')));
			}
			
			if($entry->id_contest != $this->_id_contest)
			{
				YouNet_Util::parentRedirect($this->_social->pageUrl(array('target' => $this->_contest->getDefaultTarget())));
			}
		
			if($entry->status == Core_Model_IEntry::STATUS_APPROVED || $entry->id_user == $this->_id_user)
			{
				$is_show_vote_button = true;
				if(isset($this->_id_user))
				{
					$votesTable = new Core_Model_DbTable_Votes();
					$is_voted = $votesTable->isVote($id_entry, $this->_id_user);
					$this->view->is_voted = $is_voted;

					$is_contest_running  = $this->_contest->isRunning();
					$is_allowed_vote	 = $this->_contest->isAllowedVote($this->_id_user, $entry->id);
					$is_show_vote_button = $is_allowed_vote && $is_contest_running;

					if(!$is_show_vote_button)
					{
						$this->view->is_allow_message = $this->_contest->getIsAllowedMessage();
					}
				}

				$user_link = $entry->getLink();
				if( empty($user_link) )
				{
					$userData	= YouNet_Util::getMemCache()->load('user_'.$entry->id_user);
					$userRow	= null;
					if( $userData === false)
					{
						$usersTable = new Core_Model_DbTable_Users();
						$userRow	= $usersTable->findOne($entry->id_user);
						YouNet_Util::getMemCache()->save($userRow->toArray(),'user_'.$entry->id_user);
					}
					else
					{
						$usersTable = new Core_Model_DbTable_Users();
						$userRow	= $usersTable->createRow($userData);
					}
					$user_link = $userRow->link;
				}
				$formVote	= new Tab_Form_Vote();
				$formVote->setAction($this->view->baseUrl('/tab/index/vote'));
				$formVote->populate(array('id_entry' => $id_entry));
				
				$params = $this->_helper->params($this->_params);
				
				$this->view->form = $formVote;
				$this->view->entry = $entry;
				$this->view->contest = $this->_contest;
				$this->view->user_link = $user_link;
				$this->view->extraValues = $params;
				$this->view->is_show_vote_button = $is_show_vote_button;
			}
			else
			{
				YouNet_Util::parentRedirect($this->_social->pageUrl(array('target' => 'view')));
			}
		}
	}

	/**
	 * This action is used for submit a new entry to database
	 */
	protected function _submitAction()
	{
		if(!isset($this->_id_contest))
		{
			YouNet_Util::parentRedirect($this->_social->pageUrl(array('target' => $this->_contest->getDefaultTarget())));
			return;
		}

		if(empty($this->_id_user))
		{
			YouNet_Util::parentRedirect($this->_social->pageUrl(array('target' => $this->_contest->getDefaultTarget())));
			return;
		}

		//TODO FBCONTEST-221
		$allow_submit = true;
		//@author phutp
		//@todo Session cache due to not execute query in one sesssion
		$hasUserSubmited_key = false;
		
		$hasUserSubmited_key = $this->_contest->hasUserSubmited($this->_id_user);
		
		if( $hasUserSubmited_key )
		{
			if($this->_contest->is_allow_multi_submit == 0)
			{
				$allow_submit = false;
			}
		}

		$is_allow_submit = $this->_contest->isAllowedSubmit() && $allow_submit;
		
		//Always allow to submit if user is admin of the page
		if( $this->_social->isPageAdmin() )
		{
			$is_allow_submit = true;
		}

		$fullname = '';
		$candidateInfoTable = new Core_Model_DbTable_CandidateInfo();
		$candidateInfoRowSet = $candidateInfoTable->getCandidateInfo($this->_id_user, $this->_id_contest);

		$form = new Tab_Form_Entry(null, $this->_id_contest);
		$form->setAction($this->view->pageUrl(array('target' => 'submit')));
		$this->view->validate_script = $form->getValidateScript();
		$value = array();

		$contestFieldsTable = new Core_Model_DbTable_EntryFields();
		$contestFields = $contestFieldsTable->getListFieldsBelongToContest($this->_id_contest);
		$field_ids = array();

		/* Get id of first_name, last_name etc fields from candidate info */
		foreach($contestFields as $field)
		{
			$field_ids[$field->type] = $field->id;
		}

		foreach($candidateInfoRowSet as $row)
		{
			$value[$row->id_entry_field] = $row->value;
		}
        
        if(!empty($field_ids[self::INDEX_FIRST_NAME]))
		{
			if(empty($value[$field_ids[self::INDEX_FIRST_NAME]]))
			{
				$value[$field_ids[self::INDEX_FIRST_NAME]] = $this->_user->first_name;
			}

			if(empty($value[$field_ids[self::INDEX_MIDDLE_NAME]]))
			{
				$value[$field_ids[self::INDEX_MIDDLE_NAME]] = $this->_user->middle_name;
			}

			if(empty($value[$field_ids[self::INDEX_LAST_NAME]]))
			{
				$value[$field_ids[self::INDEX_LAST_NAME]] = $this->_user->last_name;
			}
		}
		else
		{
			if(empty($value[$field_ids[self::INDEX_FULL_NAME]]))
			{
				$format = "%s %s %s";
				$fullname = sprintf(
					$format,
					trim($this->_user->first_name),
					trim($this->_user->middle_name),
					trim($this->_user->last_name)
				);
				$value[$field_ids[self::INDEX_FULL_NAME]] = $output = preg_replace('!\s+!', ' ', $fullname);
			}
		}

		if(isset($field_ids[self::INDEX_EMAIL]) && empty($value[$field_ids[self::INDEX_EMAIL]]))
		{
			$value[$field_ids[self::INDEX_EMAIL]] = $this->_user->email;
		}

		if(isset($field_ids[self::INDEX_DATE_OF_BIRTH]) && !empty($field_ids[self::INDEX_DATE_OF_BIRTH]))
		{
			$this->view->index_dob = $field_ids[self::INDEX_DATE_OF_BIRTH];
            if(!empty($value[$field_ids[self::INDEX_DATE_OF_BIRTH]])){
		        $value[$field_ids[self::INDEX_DATE_OF_BIRTH]] =
		            Core_Util::convertDateFormatFromDb2Web($value[$field_ids[self::INDEX_DATE_OF_BIRTH]]);
			}
		}

		$form->populate($value);

		$terms = Core_Util::escapeForJS($this->_contest->term_and_condition);

		$this->view->form = $form;
		$this->view->terms = $terms;
		$this->view->id_user = $this->_id_user;

		if(!$is_allow_submit)
		{
			$this->view->is_not_allow_to_submit = true;
            if($this->_contest->isWaiting())
            {
                $this->view->message = sprintf($this->view->translate('MSG_YOU_CAN_JOIN_AT'), $this->_contest->getStartDate($this->translate('DATE_FORMAT')));
            }
            else if($this->_contest->isEnd())
            {
                $this->view->message = sprintf(YouNet_Util::translate('MSG_CONTEST_IS_ENDED'), $this->_contest->getEndDate($this->translate('DATE_FORMAT')));
            }
            else
            {
                $this->view->message = $this->view->translate('MSG_DOES_NOT_ALLOW_SUBMIT');
            }
            
			if(!$allow_submit)
			{
				$this->view->message = $this->view->translate('MSG_REACH_MAX_ENTRY_NUMBER');
			}
			return;
		}

		if(!isset($_POST['form_submitted']))
		{
			return;
		}

		if( APP_INSTANCE == APP_INSTANCE_IMAGE )
		{
			$image = $form->image;

			$file_name = $image->getFileName(null, false);

			if(!empty($file_name))
			{
                $name_length = strlen($file_name);
				if($name_length > 40)
				{
					$file_name = substr($file_name, 0, 40) . substr($file_name, $name_length - 4, $name_length);
				}
				$image_name = mt_rand(10, 9999) . '_' . preg_replace('/[^A-Za-z0-9.]/i', '', $file_name);
				$image->addFilter('Rename', array('target' => UPLOAD_PATH . '/' . $image_name));
			}
		}

		if( !$form->isValid($_POST) )
		{
			return;
		}
		
		if( APP_INSTANCE == APP_INSTANCE_IMAGE )
		{
			if( !$image->receive() )
			{
				return;
			}
		}

		$entriesTable = new Core_Model_DbTable_Entries();
		$entry_params = array(
			'params' => $this->_params,			
			'id_user' => $this->_id_user,
			'id_contest' => $this->_id_contest,
			'description' => $form->getValue('description'),
            'is_need_for_approve' =>  $this->_contest->isNeedForApprove()
		);
		if( APP_INSTANCE == APP_INSTANCE_IMAGE )
		{
			$entry_params['is_image_uploaded']	= $image->isUploaded();
			$entry_params['image_name']			= $image_name;
		}

		$id_entry = $entriesTable->insertFromParams($entry_params);

		//get value such as first name, last name etc.
		$data = $form->getValues();
        $candidate_info = $data['candidate'];

		if(!empty($field_ids[self::INDEX_FIRST_NAME]))
		{
			$format = "%s %s %s";
			$fullname = sprintf(
				$format,
				trim($candidate_info[$field_ids[self::INDEX_FIRST_NAME]]),
				trim($candidate_info[$field_ids[self::INDEX_MIDDLE_NAME]]),
				trim($candidate_info[$field_ids[self::INDEX_LAST_NAME]])
			);

			if( isset($field_ids[self::INDEX_FULL_NAME]) )
			{
				$candidate_info[$field_ids[self::INDEX_FULL_NAME]] = $fullname;
			}
		}
        
        if( isset($field_ids[self::INDEX_DATE_OF_BIRTH]) && 
            !empty($candidate_info[$field_ids[self::INDEX_DATE_OF_BIRTH]])
        )
		{
            $candidate_info[$field_ids[self::INDEX_DATE_OF_BIRTH]] = 
                Core_Util::convertDateFormatFromWeb2Db($candidate_info[$field_ids[self::INDEX_DATE_OF_BIRTH]]);
		}

		$candidateInfoTable->insertFromParams($candidate_info, $this->_id_user);

		//increase submission number
		$this->_contest->submissions+=1;
		if($entriesTable->countEntryByUserWithoutStatus($this->_id_user, $this->_id_contest) == 1)
		{
			$this->_contest->registrants+=1;
		}

		$contestTlb = new Core_Model_DbTable_Contests();
		if( $this->_id_contest )
		{
			$contestTlb->update(
				array(
					'registrants' => $this->_contest->registrants,
					'submissions' => $this->_contest->submissions
				),
				array('id = ?' => $this->_id_contest)
			);
			$this->_updateCachedContest();
		}

		if( APP_INSTANCE == APP_INSTANCE_IMAGE )
		{
			$source = UPLOAD_PATH. DIRECTORY_SEPARATOR . $image_name;
			$thumbnail = THUMBNAIL_PATH . DIRECTORY_SEPARATOR . $image_name;

			//FIXME temporarily disable resize feature on cloud
			/*
			list($width, $height) = getimagesize($source);

			if($width > Core_ImageUtil::DEFAULT_IMAGE_SIZE)
			{
				$newWidth = Core_ImageUtil::DEFAULT_IMAGE_SIZE;
				$newHeight = round(($height / $width) * $newWidth);
				//reduce image size to 800px MAX
				Core_ImageUtil::resize($source, $newWidth, $newHeight);
			}
			*/
			
			// create thumbnail
			$this->_createThumbnail($source, $thumbnail);
		}

		//set thank you message
		$msg = $this->_contest->message_thanks;
		Core_Util::setLatestMessage($msg, $this->_contest->getThanksYouMgsKey());

        //FIXME Temporarily disable croping feature
        // YouNet_Util::parentRedirect($this->_social->pageUrl(array('target' => 'detail', 'id_entry' => $id_entry)));

        $approve_url = $this->_social->url('/contest/entry/detail/id_entry/' . $id_entry . "?ref=email");
        $this->_notifySubmitEntry($this->_params, $this->_contest, $approve_url);
		$this->_forward('index', null, null, array('target' => 'view', 'id_entry' => $id_entry));
	}
    
    protected function _notifySubmitEntry($params, $contest, $url)
    {
		//$id_page	= $this->_social->getPageName($this->_social->getIdPage());
        $id_page = $this->_social->getIdPage();
        $pagesTable = Core_Model_DbTable_Pages::getInstance();
        $name_page = $pagesTable->getNamePage( $id_page);

        $from       = 'support.contest@younetmedia.com';
        $template   = 'templateSubmitEntryEmail.phtml';
        $subject    = "[".$name_page. "][" . $contest['title'] . ']: New entry submission';
        $notify_email = preg_replace('/\s+/', "", $contest['notify_email']);
        if(!empty($notify_email))
        {    
            $to         = explode( ",", $notify_email);
            $user       = $this->_social->getUser();
            foreach ($to as $mod_email)
            {
                $data       = array(
                    'uploader_name' => $user['name'],
                    'url'           => $url,
                    'title'         => $params['title'],
                    'description'   => $params['description'],
                    'mod_email'     => $mod_email,
                    'contest_name'  => $contest['title']
                );
                $this->_sendEmail($from, $mod_email, $subject, $template, $data);
            }
        }
    }
    
    protected function _sendEmail($from, $to, $subject, $template, $data)
    {
        try{
            $mail			= new Zend_Mail('UTF-8');
            $admin_mail		= $from;
            $mail->setFrom($from);
            $mail->setBodyHtml($this->view->partial($template, $data));
            $mail->addTo($to);
            $mail->setSubject($subject);
            $mail->send();
        } catch (Exception $e){}
    }

	private function _createThumbnail($source, $thumbnail)
	{
		$storage = Zend_Registry::get('storage');
		if ($storage instanceof YouNet_Storage_S3)
		{
			$thumbnail_local = INDEX_PATH . '/../..' . $thumbnail;
			$storage->copyToLocal($source, $thumbnail_local);
			$this->_cropThumbnail($thumbnail_local);
			$storage->put($thumbnail, file_get_contents($thumbnail_local));
		}
		else
		{
			copy($source, $thumbnail);
			$this->_cropThumbnail($thumbnail);
		}
	}

	private function _cropThumbnail($thumbnail)
	{
		list($width, $height) = getimagesize($thumbnail);
		$min = min(array($width, $height));

		$cropWidth = $cropHeight = Core_ImageUtil::DEFAULT_IMAGE_THUMBNAIL_SIZE;
		Core_ImageUtil::crop($thumbnail, $cropWidth, $cropHeight, 0, 0, $min, $min);
	}

	protected function _imageAction()
	{
		$id_entry = $this->_getParam('id_entry');
		if(isset($id_entry))
		{
			$entriesTable = new Core_Model_DbTable_Entries();
			$entry = $entriesTable->findOne($id_entry);
			if(isset($entry))
			{
				if($entry->id_user == $this->_id_user)
				{
					$this->view->image = $image = $entry->image;
					$this->view->form = $form = new Tab_Form_Crop();

					$thumbnailPath = THUMBNAIL_PATH . DIRECTORY_SEPARATOR . $image;
					list($width, $heigth) = getimagesize($thumbnailPath);


					$x = $y = $x2 = $y2 = 0;

					$size = ($width < $heigth) ? $width : $heigth;

					$x = round($width / 2) + round($size / 2);
					$y = round($heigth / 2) + round($size / 2);
					$x2 = round($x - $size);
					$y2 = round($y - $size);

					//set default selected area
					$this->view->x	= $x;
					$this->view->y	= $y;
					$this->view->x2 = $x2;
					$this->view->y2 = $y2;

					if(isset($_POST['form_submitted']))
					{
						$cropWidth = $cropHeight = 150;
						$selectedX = $this->_getParam('x');
						$selectedY = $this->_getParam('y');
						$selectedW = $this->_getParam('w');
						$selectedH = $this->_getParam('h');

						if($selectedW >1 && $selectedH >1)
						{
							Core_ImageUtil::crop($thumbnailPath, $cropWidth, $cropHeight, $selectedX, $selectedY, $selectedW, $selectedH);
						}

						YouNet_Util::parentRedirect($this->_social->pageUrl(array('target' => 'detail', 'id_entry' => $id_entry)));
					}
				}
				else
				{
					YouNet_Util::parentRedirect($this->_social->pageUrl(array('target' => 'view')));
				}
			}
		}
	}

	protected function _likeAction()
	{
		$this->_helper->layout->setLayout('tab_facebook_like');
		if(isset($this->_contest))
		{
			$this->view->image_welcome = $this->_contest->getWelcomeImageLink();
		}
		//TODO: count the number of people that use this app
	}

	protected function _winnersAction()
	{
		if(isset($this->_id_contest))
		{
			$this->view->contest = $this->_contest;
		}
	}

    public function voteAction()
    {
        $this->disableAutoRender();
		$id_entry		= $this->_getParam('id_entry', 0);
        $result = array(
            'success' => false,
            'message' => $this->translate('MSG_VOTE_FAIL'),
            'data' => "",
            'share' => true
        );
		if(isset($this->_id_user)){
			if(!empty($id_entry)){
				$is_allowed_vote	 = $this->_contest->isAllowedVote($this->_id_user, $id_entry);
				$is_contest_running	 = $this->_contest->isRunning();
                
				if($is_contest_running && $is_allowed_vote){
					$entry = Core_Model_DbTable_Entries::getInstance()->findOne($id_entry);
					
					/* @var $contestRow Core_Model_Entry */
					if($entry->status == Core_Model_IEntry::STATUS_APPROVED)
					{
						if($entry->vote($this->_id_user) > 0){
                            $result = array(
                                'success' => true,
                                'message' => 'Vote successful!',
                                'data' => $this->view->number($entry->votes, 'LABEL_NUM_VOTE'),
                                'share' => true
                            );

                            //check auto share
                            try{
                                if ($this->_contest->is_auto_post == 1)
                                {
                                    $this->_social->postToWall(array(
                                        'message'	=> '',							
                                        'link'		=> $entry->getShareUrl(array(
                                                            'id_user_ref' => $this->_id_user
                                                        ))
                                    ));
                                    $result['share'] = false;
                                }
                            }
                            catch(Exception $e)
                            {
                                //Don't have perssmion 'publish_stream' to auto post
                                //echo "ko co quyennha " .$e ;die;
                            } 
                        }
					} else {
                        $result['message'] = $this->translate('MGS_ENTRY_CAN_NOT_FOUND');
                    }
				} else {
                    if(!$is_allowed_vote){
                        $result['message'] = $this->translate('MSG_VOTED_ALREADY_OR_CONTEST_DOES_NOT_ALLOW_MULTI_VOTE');
                    }
                }
			}
		} 
        echo json_encode($result);
    }

	/**
	 *
	 * @return Zend_Session_Namespace
	 */
	private function _getSession()
	{
		return Zend_Registry::get('session');        
	}

    protected function initReportCampaign() {
    	if( empty($this->_id_contest) )
    	{
    		$this->disableTrackingReport();
    		return;
    	}
        $this->setIdCampaign($this->_id_contest);
    }
}
